import torch
import torch.nn as nn
import torch.utils.data
import torch.nn.init
import numpy as np


n_train = 7000
n_test = 3000
num_inputs = 500
true_w = torch.ones(num_inputs, 1) * 0.0056
true_b = 0.028

features = torch.randn(n_train + n_test, num_inputs)
labels = torch.matmul(features, true_w) + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype= torch.float)

batch_size = 200
num_epochs = 20
lr = 0.01


def squared_loss(y_hat, y):
    return (y_hat - y.view(y_hat.size())) ** 2 / 2

loss = squared_loss

def train(x_train, y_train, x_valid, y_valid):
    net = nn.Linear(num_inputs, 1)
    nn.init.normal_(net.weight, mean=0, std=0.1)
    nn.init.normal_(net.bias, mean=0, std=1)
    optimizer_w = torch.optim.SGD(params=[net.weight], lr=lr)
    optimizer_b = torch.optim.SGD(params=[net.bias], lr=lr)

    train_dataset = torch.utils.data.TensorDataset(x_train,y_train)
    train_dataiter = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=0)

    valid_dataset = torch.utils.data.TensorDataset(x_valid,y_valid)
    valid_dataiter = torch.utils.data.DataLoader(dataset=valid_dataset, batch_size=batch_size, shuffle=False, num_workers=0)

    train_ls = []
    test_ls = []
    n, train_loss_sum = 0, 0
    n_test, test_loss_sum = 0, 0

    for epoch in range(num_epochs):
        for X, y in train_dataiter:
            l = loss(net(X), y).mean()
            optimizer_b.zero_grad()
            optimizer_w.zero_grad()
            l.backward()
            optimizer_w.step()
            optimizer_b.step()
            n += y.shape[0]
            train_loss_sum +=l.item()
        train_ls.append(train_loss_sum / n)

        for X, y in valid_dataiter:
            l = loss(net(X), y).mean()
            n_test += y.shape[0]
            test_loss_sum += l.item()
        test_ls.append(test_loss_sum / n)

        # print('epoch %d, w= %.4f, b= %.3f' % (epoch + 1, net.weight.mean().item(), net.bias.mean().item()))
    return train_ls, test_ls

def get_k_fold_data(k, i, X, y):
    # 返回第i折交叉验证时所需要的训练和验证数据，分开放，X_train为训练数据，X_valid为验证数据
    assert k > 1
    fold_size = X.shape[0] // k  
    X_train, y_train = None, None
    for j in range(k):
        idx = slice(j * fold_size, (j + 1) * fold_size)  #slice(start,end,step)切片函数
        X_part, y_part = X[idx, :], y[idx]
        if j == i:
            X_valid, y_valid = X_part, y_part
        elif X_train is None:
            X_train, y_train = X_part, y_part
        else:
            X_train = torch.cat((X_train, X_part), dim=0)
            y_train = torch.cat((y_train, y_part), dim=0)
    return X_train, y_train, X_valid, y_valid

def k_fold(k, X_train, y_train, num_epochs, batch_size):
    for i in range(k):
        data = get_k_fold_data(k, i, X_train, y_train) # 获取k折交叉验证的训练和验证数据
        train_ls, valid_ls = train(*data)
        train_l_sum, valid_l_sum, train_acc_sum, valid_acc_sum = 0.0, 0.0, 0.0, 0.0
        for ii in train_ls:
            train_l_sum += ii
        for jj in valid_ls:
            valid_l_sum += jj

        print('fold %d, train loss %.4f, valid loss %.4f' % (i + 1, train_l_sum / num_epochs, valid_l_sum / num_epochs))

k_fold(10, features, labels, num_epochs, batch_size)